<!--
 * @Description: file content
 * @Author: oooh
 * @Date: 2024-04-18 15:37:46
 * @LastEditors: oooh
 * @LastEditTime: 2024-06-13 09:29:13
 * @FilePath: \Civil_Servant_Performance_PC\src\views\work\cadre-work-completion\index.vue
-->
<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-select v-model="queryParams.year" placeholder="请选择" @change="handleYearChange">
          <el-option v-for="item in dict.type.biz_work_year_list" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-select v-model="queryParams.quarter" placeholder="请选择" class="ml-10" @change="handleQuarterChange">
          <el-option v-for="item in quarterOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-select
          v-hasPermi="['work:cadre-completion:list-civil']"
          v-model="queryParams.civilServantId"
          placeholder="请选择部门成员"
          class="ml-10"
          @change="getList"
        >
          <el-option v-for="item in civilList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-col>
    </el-row>
    <div class="text-banner">
      <span>干部工作纪实（共 {{ workTotal }} 条）</span>
      <el-button size="mini" type="primary" circle icon="el-icon-refresh" plain @click="getList" />
    </div>
    <div v-loading="workLoading">
      <div>
        <div class="month-title">
          <p>
            <span class="month-mark-first">{{ queryParams.quarter }}</span
            >季度工作纪实 <span class="ml-20">已分配</span><span class="month-mark-second">{{ workUsedScore }}</span
            >分
          </p>
        </div>
        <div>
          <!-- 上传提示 -->
          <div class="el-upload__tip">
            <p>
              <b style="color: #f56c6c">*完成材料：</b>大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> 格式为
              <b style="color: #f56c6c">{{ fileType.join('/') }}</b
              >的文件（不超过<b style="color: #f56c6c">{{ limit }}</b
              >项）
            </p>
          </div>
          <el-table :data="workList" border style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="props">
                <!-- <div style="padding: 10px 20px">
                  <el-card> -->
                <el-table :data="props.row.personalWorkPlanScoreList" border stripe style="width: 100%">
                  <el-table-column prop="civilServantName" label="参与人" align="center"></el-table-column>
                  <el-table-column prop="workCompletionStageDict" label="完成状态" width="160" align="center">
                    <template slot-scope="scope">
                      <el-select
                        v-show="!checkWorkPlanDisabled(scope.row.workReportMark)"
                        v-model="scope.row.workCompletionStageDict"
                        placeholder="选择完成状态"
                      >
                        <el-option v-for="item in dict.type.biz_work_completion_stage" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                      </el-select>
                      <dict-tag
                        v-show="checkWorkPlanDisabled(scope.row.workReportMark)"
                        :options="dict.type.biz_work_completion_stage"
                        :value="scope.row.workCompletionStageDict"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="workCompletionSituation" label="完成情况" min-width="180" align="center">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.workCompletionSituation"
                        type="textarea"
                        placeholder="输入完成情况"
                        :rows="1"
                        :autosize="{ minRows: 1, maxRows: 5 }"
                        v-show="!checkWorkPlanDisabled(scope.row.workReportMark)"
                      ></el-input>
                      <span v-show="checkWorkPlanDisabled(scope.row.workReportMark)" class="pre-wrap align-left">{{
                        scope.row.workCompletionSituation || '-'
                      }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column prop="workCompletionMaterialUrls" label="完成材料" min-width="180" align="center">
                    <template slot-scope="scope">
                      <FileUpload
                        v-show="!checkWorkPlanDisabled(scope.row.workReportMark)"
                        v-model="scope.row.workCompletionMaterialUrls"
                        :isShowTip="false"
                        :fileType="fileType"
                      ></FileUpload>
                      <div v-show="checkWorkPlanDisabled(scope.row.workReportMark)">
                        <div v-if="scope.row.workCompletionMaterialUrls">
                          <el-tooltip
                            v-for="(url, index) in scope.row.workCompletionMaterialUrls.split(',')"
                            :key="index"
                            effect="dark"
                            :content="formatFileUrl(url)['name']"
                            placement="top-start"
                          >
                            <el-button type="text" @click="handlePreviewFile(url)" class="file-preview-btn">
                              {{ formatFileUrl(url)['name'] }}
                            </el-button>
                          </el-tooltip>
                        </div>
                        <span v-else>-</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="workCompletionDate" label="完成日期" width="160" align="center">
                    <template slot-scope="scope">
                      <el-date-picker
                        v-model="scope.row.workCompletionDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择日期"
                        v-show="!checkWorkPlanDisabled(scope.row.workReportMark)"
                      >
                      </el-date-picker>
                      <span v-show="checkWorkPlanDisabled(scope.row.workReportMark)">{{ scope.row.workCompletionDate }}</span>
                    </template>
                  </el-table-column>
                </el-table>
                <!-- </el-card>
                </div> -->
              </template>
            </el-table-column>
            <el-table-column label="序号" type="index" align="center">
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="workType" label="任务类型" min-width="100" align="center">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.biz_work_type" :value="scope.row.workType" />
              </template>
            </el-table-column>
            <el-table-column prop="civilServantName" label="参与人" min-width="100" align="center"> </el-table-column>
            <el-table-column prop="workContent" label="具体内容" min-width="180" align="center">
              <template slot-scope="scope">
                <div class="pre-wrap align-left">{{ scope.row.workContent || '-' }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="planScore" label="分值" width="80" align="center"> </el-table-column>
            <el-table-column prop="name" label="操作" align="center" width="140">
              <template slot-scope="scope">
                <el-button type="text" v-show="scope.row.workReportMark" size="mini" class="color-success" icon="el-icon-check">[已提交]</el-button>
                <el-button
                  type="text"
                  v-show="!scope.row.workReportMark"
                  size="mini"
                  @click.stop="handleWorkPlanSaveOrSubmit(scope.row, 'save')"
                  v-hasPermi="['work:cadre-completion:save']"
                  :disabled="!isWorkEdit"
                >
                  保存
                </el-button>

                <el-button
                  type="text"
                  v-show="!scope.row.workReportMark"
                  size="mini"
                  @click.stop="handleWorkPlanSaveOrSubmit(scope.row, 'submit')"
                  v-hasPermi="['work:cadre-completion:submit']"
                  :disabled="!isWorkEdit"
                >
                  提交
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <FilePreview :visible.sync="filePreviewVisible" :file="previewFile"></FilePreview>
  </div>
</template>

<script>
import { workSaveOrSubmit, list as listPlan } from '@/api/work/work-completion/cadre.js'
import { quarterFormat, checkQuarterWorkEdit } from '@/utils/quarter.js'
import FilePreview from '@/components/FilePreview'
import FileUpload from '@/components/FileUpload'
import { mapGetters } from 'vuex'
import { list as listCivil } from '@/api/organization/civil-servant'
import dayjs from 'dayjs'
import { mixins } from '@/mixins'
export default {
  name: 'cadre-work-completion',
  props: {},
  dicts: ['biz_work_year_list', 'biz_work_type', 'biz_work_completion_stage', 'biz_dept_important_work_completion'],
  components: { FileUpload, FilePreview },
  mixins: [mixins],
  data() {
    return {
      isWorkEdit: false,
      workList: [],
      civilList: [], // 部门成员列表
      filePreviewVisible: false,
      previewFile: {},

      // 重点工作映射项
      workMapping: {
        workCompletionStageDict: '完成状态',
        workCompletionSituation: '完成情况',
        workCompletionDate: '完成日期'
      },
      workItem: {
        workScoreId: '',
        workCompletionStageDict: undefined,
        workCompletionMaterialUrls: undefined,
        workCompletionDate: dayjs().format('YYYY-MM-DD'),
        workCompletionSituation: undefined
        // remarks: undefined
      },
      workTotal: 0,
      workLoading: false,
      quarterOptions: [],
      queryParams: {
        year: '',
        quarter: ''
        // auditStatusDict: 'SHTG',
        // querySelf: true
      }
    }
  },
  computed: {
    ...mapGetters(['dept']),
    workUsedScore() {
      const sum = this.workList.reduce((prev, curr) => {
        if (curr.planScore) {
          return prev + parseInt(curr.planScore)
        } else {
          return prev
        }
      }, 0)
      return sum
    }
  },
  watch: {},
  async created() {
    let isPermi = this.$auth.hasPermi('work:cadre-completion:list-civil') // 验证用户是否有人员列表查询权限
    if (isPermi) {
      await this.getCivilList()
    }
    this.handleYearChange(new Date().getFullYear())
  },
  methods: {
    // 预览文件
    handlePreviewFile(url) {
      let fileItem = this.formatFileUrl(url)
      this.previewFile = { url, ...fileItem }
      this.filePreviewVisible = true
    },
    // 获取部门成员列表
    async getCivilList() {
      await listCivil().then(response => {
        this.civilList = response.rows.map(item => {
          return { label: item.name, value: item.id }
        })
        if (this.civilList.length) {
          this.queryParams.civilServantId = this.civilList[0].value
        } else {
          this.queryParams.civilServantId = ''
        }
      })
    },

    // 校验工作计划表单字段是否可填
    checkWorkPlanDisabled(audit) {
      return audit
    },
    // 工作纪实保存或提交校验
    handleWorkPlanSaveOrSubmitCheck(raw) {
      // for (let key of Object.keys(this.workMapping)) {
      //   if (raw[key] == '' || raw[key] == null) {
      //     this.$message.error(`操作失败，【${this.workMapping[key]}】 不能为空！`)
      //     return
      //   }
      // }

      let params = { id: raw.id, personalWorkResultList: [] }
      // 根据工作类型填充对应参数
      let keys = Object.keys(this.workItem)

      params.personalWorkResultList = raw.personalWorkPlanScoreList.map(item => {
        let temp = {}
        for (let key of keys) {
          temp[key] = item[key]
        }
        return temp
      })
      return params
    },
    // 工作计划保存或提交
    async handleWorkPlanSaveOrSubmit(raw, operationType = 'save') {
      let params = await this.handleWorkPlanSaveOrSubmitCheck(raw)
      if (!params) return
      params.workReportMark = false

      if (operationType === 'submit') {
        params.workReportMark = true
        let isPrompt = false
        let keys = Object.keys(this.workMapping)
        for (let item of raw.personalWorkPlanScoreList) {
          for (let key of keys) {
            if (!item[key]) isPrompt = true
          }
        }
        if (isPrompt) {
          let isBreak = await this.$modal
            .confirm('当前提交任务有未填写的纪实内容，是否继续提交？')
            .then(() => false)
            .catch(() => true)
          if (isBreak) return
        }
      }
      // 保存或提交工作纪实
      await workSaveOrSubmit(params).then(res => {
        if (operationType === 'save') {
          this.$modal.msgSuccess('工作纪实已保存')
        } else if (operationType === 'submit') {
          this.$modal.msgSuccess('工作纪实已提交')
        }
      })

      this.getList()
    },

    // 年度选择
    handleYearChange(year) {
      this.queryParams.year = year
      // 获取当前季度、季度列表（往年默认第一季度）
      let { quarter, quarterList } = quarterFormat(year)
      this.quarterOptions = quarterList
      this.handleQuarterChange(quarter)
    },
    // 季度选择
    handleQuarterChange(quarter) {
      this.queryParams.quarter = quarter
      checkQuarterWorkEdit({ year: this.queryParams.year, quarter }).then(res => {
        this.isWorkEdit = res
      })
      this.getList()
    },
    getList() {
      this.getWorkList()
    },
    // 表格数据处理
    tableFormat(list) {
      for (let item of list) {
        item.civilServantName = item.personalWorkPlanScoreList
          .map(civil => {
            return civil.civilServantName
          })
          .join('、')
        item.personalWorkPlanScoreList.forEach(element => {
          element.workReportMark = item.workReportMark
          if (!element.workCompletionDate) element.workCompletionDate = dayjs().format('YYYY-MM-DD')
        })
      }
      this.workList = list
    },
    // 工作纪实列表
    getWorkList() {
      this.workLoading = true
      listPlan({ ...this.queryParams })
        .then(res => {
          let { data } = res
          this.workTotal = data.length
          this.tableFormat(data)
          this.workLoading = false
        })
        .catch(err => (this.workLoading = false))
    }
  }
}
</script>

<style lang="scss" scoped>
@import url('~@/assets/styles/work.scss');
::v-deep .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: auto;
}

::v-deep .el-input-number--medium {
  width: auto;
}

::v-deep .el-button [class*='el-icon-'] + span {
  margin-left: 0;
}
::v-deep .el-table__expanded-cell {
  background-color: #fafafa;
  padding: 15px;
}
.file-preview-btn {
  width: 100%;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  margin-left: 0;
  padding: 0;
}
</style>
